package com.test.validation;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.opensymphony.xwork2.validator.ValidationException;
import com.opensymphony.xwork2.validator.validators.FieldValidatorSupport;

public class DateRangeValidator extends FieldValidatorSupport {
	private String format = "yyyy-MM-dd";
	private String min;

	public String getMin() {
		return min;
	}

	public void setMin(String min) {
		this.min = min;
	}

	public String getMax() {
		return max;
	}

	public void setMax(String max) {
		this.max = max;
	}

	private String max;

	public void validate(Object object) throws ValidationException {
		String fieldName = getFieldName();
		Object fieldValue = getFieldValue(fieldName, object);
		if (fieldValue == null) {
			return;
		}
		if (format == null) {
			throw new ValidationException("format parameter is required!");
		}
		SimpleDateFormat dateFmt = new SimpleDateFormat(format);
		Date srcDate, minDate, maxDate = null;
		try {
			if (fieldValue instanceof Date) {
				srcDate = (Date) fieldValue;
			} else {
				srcDate = dateFmt.parse((String) fieldValue);
			}
		} catch (ParseException e) {
			throw new ValidationException(e.getMessage());
		}
		if (min == null && max == null) {
			return;
		}
		if (min != null) {
			try {
				minDate = dateFmt.parse(min);
				if (minDate.compareTo(srcDate) >= 0) {
					addFieldError(fieldName, object);
				}
			} catch (ParseException e) {
				throw new ValidationException(e.getMessage());
			}
		}
		if (max != null) {
			try {
				maxDate = dateFmt.parse(max);
				if (maxDate.compareTo(srcDate) <= 0) {
					addFieldError(fieldName, object);
				}
			} catch (ParseException e) {
				throw new ValidationException(e.getMessage());
			}
		}
	}
}
